package com.cyzy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.mapper.OrderMapper;
import com.cyzy.pojo.Orders;
import com.cyzy.service.OrderService;
import com.cyzy.utils.Timer;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private Timer timer;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Integer addOrder(Orders order) {
        order.setOrderType("商城");
        order.setRelatedId(1);
        order.setOrderStatus(2);
        ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.systemDefault());
        Long timestamp = zonedDateTime.toInstant().toEpochMilli();
        order.setOrderNum("PRO" + timestamp);

        int num = orderMapper.insert(order);
        if (num>0){
//            redisTemplate.opsForValue().set("product_order_id="+order.getOrderId(),
//                    JSON.toJSONString(order),1, TimeUnit.MINUTES);
//            timer.checkKeyAfterDelay("product_order_id="+order,60 * 1000);

            String dataKey = "product:order:data:" + order.getOrderId();
            // 定时Key（设置过期时间）
            String timerKey = "product:order:timer:data:" + order.getOrderId();
            redisTemplate.opsForValue().set(dataKey, JSON.toJSONString(order));

            // 存储定时Key（设置过期时间）
            redisTemplate.opsForValue().set(timerKey, JSON.toJSONString(order), 1, TimeUnit.MINUTES);
//            rocketMQTemplate.syncSend("DELAY_CHECK_TOPIC",
//                    MessageBuilder.withPayload(timerKey)
//                            .setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "5") // RocketMQ延迟级别
//                            .build()
//            );
        }

        return timestamp.intValue();
    }

    @Override
    public Integer updateOrder(Orders order) {
        return orderMapper.updateById(order);
    }

    @Override
    public Orders getOrderById(Integer id) {
        return null;
    }

    @Override
    public List<Orders> getAllOrders() {
        return List.of();
    }
}
